<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */
defined ('IN_AGORA') or die;

class TaskController extends AgoraController
{
	// default controller call - show topics and subforums
	function __construct()
	{
		parent::__construct();
		$this->loadDefaultView();
	}

	// extract parent forums and categories path from common forumList array and publish it to template
	function _buildPathWay($forum)
	{
		$parent_id = $forum['parent_forum_id'];
		$cat_id = $forum['cat_id'];

		$pathway = & $this->helper('pathway');

		while ($parent_id != 0) {
			$parent_forum = $this->forumList[$cat_id]['forums'][$parent_id];
			$pathway->push($parent_forum['forum_name'],Agora::makeURL(array('task' => 'forum', 'id' => $parent_forum['id'])));
			$parent_id = $parent_forum['parent_forum_id'];
		};

		// prepend with category
		$pathway->push($forum['cat_name'],Agora::makeURL(array('id' => $cat_id)));

		// append current forum without link - user already has link in his browser
		$pathway->add($forum['forum_name'],'');
	}

	function _setHeadTags($forum)
	{
		$document = & JFactory::getDocument();
		$document->setTitle($forum['forum_name']);
		$document->setMetaData ('keywords', $forum['forum_key']);
		$document->setDescription($forum['forum_mdesc']);
	}

	function _rss()
	{
		$forum_model = & Model::getInstance('ForumModel');
		$forum_id = (int)Agora::getVar('forum_id');

		$topics = $this->forum->getFeed($forum_id,30);
		$this->view->assign('topics',$topics);
		$this->view->template = 'forum';
	}

	function _loadSubforums($category_id, $forum_id)
	{
		$subforums = array();

		$ids = array();
		if ($this->forumList && isset($this->forumList[$category_id]) && isset($this->forumList[$category_id]['forums'])) {
			foreach ($this->forumList[$category_id]['forums'] as $forum) {
				if ($forum['id'] == $forum_id) {
					$parent_level = $forum['level'];
					continue;
				}

				if (!isset($parent_level)) {
					continue;
				}

				if ($forum['level'] <= $parent_level) {
					// next sibling
					break;
				}
				if ($forum['level'] == $parent_level+1) {
					$subforums[$forum['id']] = $forum;
					$parent = & $subforums[$forum['id']];
					$parent['subforums'] = array();
					$ids[] = $forum['id'];
					
				} elseif ($forum['level'] == $parent_level+2) {
					$parent['subforums'][$forum['id']] = $forum;
				}
			}
		}
		$forum_helper = &$this->helper('forum');
		return $forum_helper->processForums($subforums);
	}
	
	function _checkSchedule($forum) // Check for expired forums
	{
		if ((!$forum['enable_sched']) || (!$forum['expires'])) // Not enabled or no Date set
			return $forum['closed'] ;
			
		$registry =& JFactory::getConfig();
		$tzdefault = $registry->getValue('config.offset');
		jimport('joomla.utilities.date');
			
		$newDate = JFactory::getDate($date);
		$newDate->setOffset($tzdefault);
			 
		$curdatetime =  $newDate->toUnix(true); //Current datetime, site time zone
		
		if ($curdatetime >= $forum['expires']) { //Expired Forum, gotta close it.
			$forum_model = & Model::getInstance('ForumModel');
			if ($forum_model->expireForum($forum['id']))
				$forum['closed'] = 1;
		}
		return $forum['closed'];
	}
	
	function _default() {
	
		if (Agora::isFeed()) {
			$this->_rss();
			return;
		}

		$forum_id = (int)Agora::getVar('id');
		
		$sort_dir = Agora::getVar('filter_order_Dir','DESC');
		$sort_field = Agora::getVar('filter_order');
		
		// sanity checks
		if (strcasecmp($sort_dir,'asc') != 0 && strcasecmp($sort_dir,'desc')) {
			$sort_dir = 'asc';
		}

		if (!in_array($sort_field,array('t.id','t.num_replies','t.last_post'))) {
			$sort_field = null;
		}

		$this->authenticate($forum_id,'read');

		$forum_model = & Model::getInstance('ForumModel');

		$forum = $forum_model->load($forum_id);

		$forum['subscribed'] = $forum_model->isSubscribed($forum_id, $this->agora_user['id']);
		$forum['closed'] = $this->_checkSchedule($forum);
		
		$this->_buildPathWay($forum);
		
		$cat_id = $forum['cat_id'];
		$catnav_helper = & $this->helper('catnav');
		$catnav_helper->fromCategory($cat_id);

		$per_page = intval($this->agora_user['disp_topics']) > 0 ? $this->agora_user['disp_topics'] : intval($this->agora_config['o_disp_topics_default']);
		$num_pages = ceil(($forum['num_topics'] + 1)/ $per_page);
		$this->setPagination($num_pages);

		$page = Agora::getPage($num_pages);
		

		$topics = $forum_model->loadTopics($forum_id, $per_page, $page, $sort_field != null ? $sort_field : 'last_post', $sort_dir);

		$t_helper = & $this->helper('topic');
		$topics = $t_helper->processRatings($topics);
		$topics = $t_helper->processTopics($topics);


		//var_dump($topics);die;
		//$sub_forums = $forum_model->loadSubforums($forum_id);
		$sub_forums = $this->_loadSubforums($forum['cat_id'],$forum_id);

		// access_model is a member of AgoraController class
		// we filter forums here with respect to user's access rights
		if (!$this->agora_user['is_superadmin']) {
			$this->access_model->filterForums($sub_forums, $this->agora_user['id']);
			$access = $this->access_model->getForumAccess($forum_id,$this->agora_user['id']);
		} else {
			$access = array();
			foreach ($this->access_model->access as $name) {
				$access[$name] = 1;
			}
			$access['use_captcha'] = 0;
		}

		if ($this->agora_user['is_guest']) {
			$banned = false;
		} else {
			$ban_model = &Model::getInstance('BanModel');
			$banned = $ban_model->isBanned($this->agora_user['username']);
		}
		
		if (($banned) || ($forum['closed'] ) ) {
			$access['post_topic'] = false;
			$access['post_poll'] = false;
			$access['post_reply'] = false;
            $access['can_moderate'] = false;
		}

		$this->view->assign('access',$access);

		$this->view->assign('sub_forums',$sub_forums);
		$this->view->assign('star_path',Agora::getRoot()."img/rate_stars/default_stars/");
		$this->view->assign('forum',$forum);
		$this->view->assign('topics',$topics);

		$this->view->template = 'forum';
	}

	function mark_read() {
		$forum_id = (int)Agora::getVar('id');
		$topic_model = & Model::getInstance('TopicModel');
		$topic_model->markForumRead($this->agora_user['id'],  $forum_id, $this->agora_config['o_timeout_visit'] * 86400);
        $this->redirect('id','!action','!page');
	}
	
	function subscribe_forum() {
		$forum_id = (int)Agora::getVar('id');
		
		$subscription_model = & Model::getInstance('SubscriptionModel');
		
		$id = $subscription_model->add(array('user_id'=>$this->agora_user['id'],'forum_id'=>$forum_id));

		Agora::showMessage(Agora::lang('You are now subscribed to this Forum '));
		
        $this->redirect('id','!action','!page');
	}
	
	function unsubscribe_forum() {
		$forum_id = (int)Agora::getVar('id');

		$subscription_model = & Model::getInstance('SubscriptionModel');
		$subscription_model->delete_forum($this->agora_user['id'], $forum_id);

		Agora::showMessage(Agora::lang('You are now unsubscribed from forum '));
		//$this->redirect('id');
		Agora::redirect($_SERVER['HTTP_REFERER']);
	}
}
?>
